package com.zcy.datasource;

import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Created by join on 2017/7/3.
 */

public class RwDataSource extends AbstractRoutingDataSource {

    private static int i = 0;

    @Override
    protected Object determineCurrentLookupKey() {

        String type = DynamicDataSourceContextHolder.getDataSourceType();
        if(StringUtils.isEmpty(type)
                || DynamicDataSourceContextHolder.WRITE_TYPE.equals(type)
                || DynamicDataSourceContextHolder.readSourceIds.size() == 0){
            return DynamicDataSourceContextHolder.getDataSourceType();
        }else{
            //此处可优化成就近原则获取数据源，根据DNS寻址+负载加权计算
            i++ ;
            i = i % DynamicDataSourceContextHolder.readSourceIds.size();
            return DynamicDataSourceContextHolder.readSourceIds.get(i);
        }

    }


}
